/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* newhead = nullptr, * newtail = nullptr;
        int next = 0;
        while (l1 || l2 || next)
        {
            int n1 = l1 ? l1->val : 0;
            int n2 = l2 ? l2->val : 0;
            int key = (n1 + n2 + next) % 10;
            next = (n1 + n2 + next) / 10;
            ListNode* newnode = new ListNode(key);
            if (newhead == nullptr) newhead = newtail = newnode;
            else
            {
                newtail->next = newnode;
                newtail = newnode;
            }
            if (l1)
                l1 = l1->next;
            if (l2)
                l2 = l2->next;
        }
        return newhead;
    }
};